﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Controls;
using VAdvantage.Model;
using VAdvantage.Utility;
using VAdvantage.Logging;
using VAdvantage.Classes;
using System.Data;
using VAdvantage.Common;
using System.Threading;
using System.ComponentModel;
using VAdvantage.DataBase;
using System.Windows.Data;

namespace VAdvantage.Framework
{
    public partial class EnterNewLocationORAddress : ChildWindow
    {
        #region PrivateVariables
        //private variable to store new record 
        //location from database
        private string _strLocationText;
        //variables to set value from dropdowns
        string country = "";
        string state = "";
        //Empty array variable to empty state drop down
        string[] dsBlank = { };
        //Null data set to empty state drop down 
        //but it  is havvy approch so use array
        //DataSet dsBlank = null;
        //VAddressTextBox.VAddressTextBox addTextBoxObj = null;

        private bool _change = false;
        private MLocation _location;
        private MLocation _tempLocation;//= new MLocation(Env.GetCtx(), 0, null); commented for SL
        private int _origCountry_ID;
        private int _oldCountry_ID = 0;

        /**	Logger			*/
        private static VLogger log = VLogger.GetVLogger(typeof(EnterNewLocationORAddress).FullName);



        #endregion

        #region Property....
        /// <summary>
        /// store full address of a location
        /// </summary>
        public string LocationText
        {
            get
            {
                //return location Text
                return _strLocationText;
            }
            set
            {
                //set location Text
                _strLocationText = value;
            }
        }
        /// <summary>
        /// location id for new record 
        /// </summary>
        public int LOCATION_ID
        {
            get;
            set;
        }

        #endregion

        #region Class Constructor
        /// <summary>
        /// class Constructor
        /// </summary>
        //Commented for SL

        void EnterNewLocationORAddress_Loaded(object sender, RoutedEventArgs e)
        {
            this.Background = new SolidColorBrush(DataBase.GlobalVariable.WINDOW_BACK_COLOR);
            FillSearchCountry();
            //LoadOld();
            LoadNew();

        }


        public EnterNewLocationORAddress(String title, MLocation location)
        //: base(false, false, false, title) commented for SL
        {
            this.Loaded += new RoutedEventHandler(EnterNewLocationORAddress_Load);
            try
            {
                InitializeComponent();
            }
            catch (Exception ex)
            {
                log.Log(Level.SEVERE, ex.Message);
            }
            _location = location;

            //get message from control
            string strAddr = Msg.GetMsg(Envs.GetCtx(), "Address", true);

            //show address text in the lable1
            lblAdd1.Content = Msg.GetMsg(Envs.GetCtx(), "Address1", true);
            //show address text in the lable2
            lblAdd2.Content = Msg.GetMsg(Envs.GetCtx(), "Address2", true);
            //show address text in the lable3
            lblAdd3.Content = Msg.GetMsg(Envs.GetCtx(), "Address3", true);
            //show address text in the lable4
            lblAdd4.Content = Msg.GetMsg(Envs.GetCtx(), "Address4", true);

            //show city text in the lable
            lblCity.Content = Msg.GetMsg(Envs.GetContext(), "City", true);

            //show the country in the lable
            lblCountry.Content = Msg.GetMsg(Envs.GetContext(), "Country", true);

            //show the country in the lable
            lblState.Content = Msg.GetMsg(Envs.GetContext(), "State", true);

            //show the Zip text
            lblZip.Content = Msg.GetMsg(Envs.GetContext(), "Postal", true);
            lblPostalAdd.Content = Msg.GetMsg(Envs.GetContext(), "PostalAdd");

            vlblSearchCountry.Content = Msg.GetMsg(Envs.GetContext(), "Country");
            vlblSearchZipCode.Content = Msg.GetMsg(Envs.GetContext(), "ZipCode");
            this.Show();
            // });
            // });
        }

        #endregion

        #region Parametrised Constructor
        //This logic for dropDown Control
        //public EnterNewLocationORAddress(VAddressTextBox.VAddressTextBox ctrl)
        //{
        //    InitializeComponent();
        //    addTextBoxObj = ctrl;
        //    LocationID = addTextBoxObj.LocationID;
        //}
        #endregion

        #region Form Load
        /// <summary>
        /// Form load
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void EnterNewLocationORAddress_Load(object sender, EventArgs e)
        {
            this.Background = new SolidColorBrush(DataBase.GlobalVariable.WINDOW_BACK_COLOR);
            //LoadOld();
            FillSearchCountry();
            LoadNew();

        }

        private void LoadNew()
        {
            this.Cursor = Cursors.Wait;

            OKButton.IsEnabled = false;
            CancelButton.IsEnabled = false;

            object[] aryCountry = null;
            object[] aryRegion = null;

            MCountry.SetDisplayLanguage(Envs.GetAD_Language(Envs.GetCtx()));


            BackgroundWorker bgw = new BackgroundWorker();

            bgw.DoWork += (sd, ed) =>
            {
                _tempLocation = new MLocation(Envs.GetCtx(), 0, null);

                if (_location == null)
                {
                    _location = _tempLocation;
                }
                aryCountry = MCountry.GetCountries(Envs.GetCtx());
                _origCountry_ID = _location.GetC_Country_ID();
                aryRegion = MRegion.GetRegions(Envs.GetContext(), _origCountry_ID);
                // });

            };


            bgw.RunWorkerCompleted += (sc, ec) =>
            {
                if (_location.GetC_Location_ID() == 0)
                    Title = Msg.GetMsg(Envs.GetCtx(), "LocationNew");
                else
                    Title = Msg.GetMsg(Envs.GetCtx(), "LocationUpdate");


                FillComboBox(this.vcmbCountry, aryCountry);

                vcmbCountry.SelectedItem = _location.GetCountry();

                FillComboBox(this.vcmbState, aryRegion);

                //fRegion = new CComboBox(MRegion.getRegions(Env.getCtx(), m_origCountry_ID));
                if (_location.GetCountry().IsHasRegion())
                    lblState.Content = _location.GetCountry().GetRegionName();	//	name for region
                vcmbState.SelectedItem = _location.GetRegion();
                InitLocation();

                this.Cursor = Cursors.Arrow;
                OKButton.IsEnabled = true;
                CancelButton.IsEnabled = true;

                bgw = null;

            };
            bgw.RunWorkerAsync();
        }

        /// <summary>
        /// Dynanmic Init & fill fields - Called when Country changes!
        /// </summary>
        private void InitLocation()
        {
            MCountry country = _location.GetCountry();
            log.Fine(country.GetName() + ", Region=" + country.IsHasRegion() + " " + country.GetDisplaySequence()
                + ", C_Location_ID=" + _location.GetC_Location_ID());
            //	new Region
            if (_location.GetC_Country_ID() != _oldCountry_ID && country.IsHasRegion())
            {
                //fRegion = new CComboBox(MRegion.getRegions(Env.getCtx(), country.getC_Country_ID()));
                //commented for SL
                //FillComboBox(vcmbState, MRegion.GetRegions(Envs.GetContext(), country.GetC_Country_ID()));
                if (_location.GetRegion() != null)
                {
                    // fRegion.setSelectedItem(m_location.getRegion());
                    vcmbState.SelectedItem = _location.GetRegion();
                }
                lblState.Content = country.GetRegionName();
                //lRegion.setText(country.getRegionName());
                _oldCountry_ID = _location.GetC_Country_ID();
            }


            RenderCountrySpecificFields();

            //  Country Last
            //line = 9;
            //addLine(line++, lCountry, fCountry);

            //	Fill it
            if (_location.GetC_Location_ID() != 0)
            {
                txtAdd1.SetValue(_location.GetAddress1());
                txtAdd2.SetValue(_location.GetAddress2());
                txtAdd3.SetValue(_location.GetAddress3());
                txtAdd4.SetValue(_location.GetAddress4());


                txtCity.SetValue(_location.GetCity());
                //fCity.setText(m_location.getCity());
                txtZip.SetValue(_location.GetPostal());
                //fPostal.setText(m_location.getPostal());
                txtPostalAdd.SetValue(_location.GetPostal_Add());
                //fPostalAdd.setText(m_location.getPostal_Add());
                if (_location.GetCountry().IsHasRegion())
                {
                    lblState.Content = _location.GetCountry().GetRegionName();
                    //lRegion.setText(m_location.getCountry().getRegionName());
                    vcmbState.SelectedItem = _location.GetRegion();
                    //fRegion.setSelectedItem(m_location.getRegion());
                }
                vcmbCountry.SelectedItem = country;
                //fCountry.setSelectedItem(country);
            }
            //	Update UI
            //pack();
        }	//	initLocation


        private void FillComboBox(Controls.VComboBox cmb, object[] items)
        {
            //cmb.Items.Clear();
            cmb.ItemsSource = items;
        }

        #endregion

        /// <summary>
        /// * 	Get edited Value (MLocation)
        /// </summary>
        /// <returns></returns>
        public MLocation GetValue()
        {
            return _location;
        }
        /// <summary>
        /// *	Get result
        /// </summary>
        /// <returns></returns>
        public bool IsChanged()
        {
            return _change;
        }

        #region Button Save/Update
        /// <summary>
        /// Button click Event 
        /// to Save and update record in data base

        private void BtnClickNew()
        {

            Action_OK();
            _change = true;

            //this.Close();
        }


        /// <summary>
        /// OK - check for changes (save them) & Exit
        /// </summary>
        private void Action_OK()
        {
            _location.SetAddress1(txtAdd1.Text);
            _location.SetAddress2(txtAdd2.Text);
            _location.SetAddress3(txtAdd3.Text);// fAddress3.getText());
            _location.SetAddress4(txtAdd4.Text);
            _location.SetCity(txtCity.Text);// fCity.getText());
            _location.SetPostal(txtZip.Text);// fPostal.getText());
            _location.SetPostal_Add(txtPostalAdd.Text);// fPostalAdd.getText());
            //  Country/Region
            MCountry c = (MCountry)vcmbCountry.SelectedItem;// fCountry.getSelectedItem();
            _location.SetCountry(c);
            if (_location.GetCountry().IsHasRegion())
            {
                MRegion r = (MRegion)vcmbState.SelectedItem;
                _location.SetRegion(r);
            }
            else
                _location.SetC_Region_ID(0);
            //	Save chnages
            ThreadPool.QueueUserWorkItem(delegate
            {
                _location.Save();
                Dispatcher.BeginInvoke(delegate
                {
                    this.Cursor = Cursors.Arrow;
                    this.DialogResult = true;
                });
            });
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            //this is to close current window
            _change = false;
            this.DialogResult = false;
        }

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            this.Cursor = Cursors.Wait;
            BtnClickNew();
            //  this.DialogResult = true;

        }
        #endregion

        #region Country dropdown SelectedIndexChanged Event
        /// <summary>
        /// vcmbCountry_SelectedIndexChanged:this is a event
        /// which check value for country
        /// </summary>
        /// 
        private void vcmbCountry_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //call state funtion on dropdown index change event
            //GetState();
            //	Country Changed - display in new Format
            //	Modifier for Mouse selection is 16  - for any key selection 0
            object[] aryRegion = null;
            if (vcmbCountry.SelectedItem == null)
            {
                return;
            }
            MCountry c = (MCountry)vcmbCountry.SelectedItem;
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                _origCountry_ID = c.GetC_Country_ID();
                aryRegion = MRegion.GetRegions(Envs.GetContext(), _origCountry_ID);
                Dispatcher.BeginInvoke(delegate
                {
                    FillComboBox(this.vcmbState, aryRegion);
                    this.vcmbState.SelectedItem = region;
                    _location.SetCountry(c);
                    RenderCountrySpecificFields();
                });
            });
        }


        /// <summary>
        /// Change control position according to country address format
        /// </summary>
        private void RenderCountrySpecificFields()
        {
            LayoutContent.Children.Remove(lblCity);
            LayoutContent.Children.Remove(txtCity);
            LayoutContent.Children.Remove(lblZip);
            LayoutContent.Children.Remove(txtZip);
            LayoutContent.Children.Remove(lblPostalAdd);
            LayoutContent.Children.Remove(txtPostalAdd);
            LayoutContent.Children.Remove(lblState);
            LayoutContent.Children.Remove(vcmbState);


            MCountry country = _location.GetCountry();

            //  sequence of City Postal Region - @P@ @C@ - @C@, @R@ @P@
            String ds = country.GetDisplaySequence();
            if (ds == null || ds.Length == 0)
            {
                log.Log(Level.SEVERE, "DisplaySequence empty - " + country);
                ds = "";	//	@C@,  @P@
            }
            int line = 5;
            StringTokenizer st = new StringTokenizer(ds, "@", false);
            while (st.HasMoreTokens())
            {
                String s = st.NextToken();
                if (s.StartsWith("C"))
                    AddControl(line++, lblCity, txtCity);
                else if (s.StartsWith("P"))
                    AddControl(line++, lblZip, txtZip);
                else if (s.StartsWith("A"))
                    AddControl(line++, lblPostalAdd, txtPostalAdd);
                else if (s.StartsWith("R") && _location.GetCountry().IsHasRegion())
                    AddControl(line++, lblState, vcmbState);
            }


        }

        private void AddControl(int line, Control left, Control right)
        {
            if (LayoutContent.Children.Contains(left))
                return;
            Grid.SetRow(left, line);
            Grid.SetColumn(left, 1);
            Grid.SetRow(right, line);
            Grid.SetColumn(right, 3);
            Grid.SetColumnSpan(right, 5);
            LayoutContent.Children.Add(left);
            LayoutContent.Children.Add(right);
        }

        #endregion
        /// <summary>
        /// ///////////////////////////////////////////////////
        /// </summary>
        public EnterNewLocationORAddress()
        {
            InitializeComponent();
        }

        public void FillSearchCountry()
        {
            DataSet ds = null;
            BackgroundWorker bgwCountry = new BackgroundWorker();
            MCountry m_country = null;
            int defaultCountry =0;
            bgwCountry.DoWork += (se, ed) =>
            {
                string sql = "select name,C_Country_ID from c_country where isactive='Y' order by name";
                ds = DB.ExecuteDataset(sql, null);
                defaultCountry= Util.GetValueOfInt(Envs.GetCtx().Get("P|C_Country_ID"));
                m_country = new MCountry(Envs.GetCtx(), defaultCountry, null);
            };

            bgwCountry.RunWorkerCompleted += (s, e) =>
            {
                if (ds == null || ds.Tables[0].Rows.Count == 0)
                {
                    return;
                }
                vcmbSearchCountry.DisplayMemberPath = "NAME";
                vcmbSearchCountry.ValueMemberPath = "C_COUNTRY_ID";
                BindingSource source = new BindingSource(ds.Tables[0].GetBindableData(new Connector()));
                vcmbSearchCountry.ItemsSource = source;
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    if (Util.GetValueOfInt(ds.Tables[0].Rows[i]["C_COUNTRY_ID"]) == defaultCountry)
                    {
                        vcmbSearchCountry.SelectedIndex = i;
                        break;
                    }
                }

                
            };
            bgwCountry.RunWorkerAsync();
        }

        public void GetZipCodeDetails()
        {
            BindableObject objcmbSelected = vcmbSearchCountry.SelectedItem as BindableObject;
            int selectedCountry = Util.GetValueOfInt(((BindableObject)objcmbSelected).GetValue("C_COUNTRY_ID"));
            BackgroundWorker bwFillControl = new BackgroundWorker();
            DataSet ds = null;
            string txt = vtxtSearchZip.Text;
            bwFillControl.DoWork += (se, ev) =>
            {
                string Sql = @" SELECT Area.name,Area.subname, country.c_country_id, region.c_region_id,area.postal, city.name as CityName, country.name as CountryName, region.name as regionName
                                   FROM c_area area
                                JOIN C_City city
                                     ON city.c_city_id=area.C_City_ID
                                JOIN c_region region
                                     ON region.c_region_id=city.c_region_id
                                JOIN c_Country country
                                     ON Country.c_country_id= city.c_country_id
                        where City.c_country_id=" + selectedCountry + " and area.postal='" + txt + "' ";
                ds = DB.ExecuteDataset(Sql, null);
            };
            bwFillControl.RunWorkerCompleted += (s, e) =>
            {
                if (ds == null || ds.Tables[0].Rows.Count == 0)
                {
                    ClearData();
                    return;
                }
                if (ds.Tables[0].Rows.Count == 1)
                {
                    FillLocation(ds);
                }
                else
                {
                    LocationSet location = new LocationSet(ds);
                    location.Show();
                    location.Closing += new EventHandler<CancelEventArgs>(location_Closing);
                }
                bwFillControl = null;
            };
            bwFillControl.RunWorkerAsync();
        }

        MCountry mcountry = null;
        MRegion region = null;
        string postal = string.Empty;
        string name = string.Empty;
        string subname = string.Empty;

        public void FillLocation(DataSet ds)
        {
            if (ds.Tables[0].Rows[0]["C_COUNTRY_ID"] != null && ds.Tables[0].Rows[0]["C_COUNTRY_ID"].ToString() != "")
            {
                System.Threading.ThreadPool.QueueUserWorkItem(delegate
                {
                    mcountry = new MCountry(Envs.GetCtx(), Convert.ToInt32(ds.Tables[0].Rows[0]["C_COUNTRY_ID"]), null);
                    Dispatcher.BeginInvoke(delegate
                    {

                        if (mcountry != null)
                        {
                            vcmbCountry.SelectedItem = mcountry;
                        }
                        else
                        {
                            vcmbCountry.SelectedIndex = -1;
                        }
                    });
                });
            }
            if (ds.Tables[0].Rows[0]["C_REGION_ID"] != null && ds.Tables[0].Rows[0]["C_REGION_ID"].ToString() != "")
            {
                System.Threading.ThreadPool.QueueUserWorkItem(delegate
                {
                    region = new MRegion(Envs.GetCtx(), Convert.ToInt32(ds.Tables[0].Rows[0]["C_REGION_ID"]), null);
                    Dispatcher.BeginInvoke(delegate
                    {
                        if (region != null)
                        {
                            vcmbState.SelectedItem = region;
                        }
                        else
                        {
                            vcmbState.SelectedIndex = -1;
                        }
                    });
                });
            }

            if (ds.Tables[0].Rows[0]["POSTAL"] != null && ds.Tables[0].Rows[0]["POSTAL"].ToString() != "")
            {
                txtZip.Text = ds.Tables[0].Rows[0]["POSTAL"].ToString();
            }
            else
            {
                txtZip.Text = "";
            }
            if (ds.Tables[0].Rows[0]["NAME"] != null && ds.Tables[0].Rows[0]["NAME"].ToString() != "")
            {
                txtAdd4.Text = ds.Tables[0].Rows[0]["NAME"].ToString();
            }
            else
            {
                txtAdd4.Text = "";
            }
            if (ds.Tables[0].Rows[0]["SUBNAME"] != null && ds.Tables[0].Rows[0]["SUBNAME"].ToString() != "")
            {
                txtAdd3.Text = ds.Tables[0].Rows[0]["SUBNAME"].ToString();
            }
            else
            {
                txtAdd3.Text = "";
            }
            if (ds.Tables[0].Rows[0]["CITYNAME"] != null && ds.Tables[0].Rows[0]["CITYNAME"].ToString() != "")
            {
                txtCity.Text = ds.Tables[0].Rows[0]["CITYNAME"].ToString();
            }
            else
            {
                txtCity.Text = "";
            }
        }

        void location_Closing(object sender, CancelEventArgs e)
        {
            LocationSet location = sender as LocationSet;
            if (location.DialogResult != null)
            {
                if ((bool)location.DialogResult)
                {
                    if (location.Country != null)
                    {
                        vcmbCountry.SelectedItem = location.Country;
                    }
                    else
                    {
                        vcmbCountry.SelectedIndex = -1;
                    }
                    if (location.Region != null)
                    {
                        region= location.Region;
                        vcmbState.SelectedItem = region;
                    }
                    else
                    {
                        vcmbState.SelectedIndex = -1;
                    }
                    if (location.Postal != null)
                    {
                        txtZip.Text = location.Postal;
                    }
                    else
                    {
                        txtZip.Text = "";
                    }
                    if (location.SubName != null)
                    {
                        txtAdd3.Text = location.SubName;
                    }
                    else
                    {
                        txtAdd3.Text = "";
                    }
                    if (location.Name != null)
                    {
                        txtAdd4.Text = location.Name;
                    }
                    else
                    {
                        txtAdd4.Text = "";
                    }
                    if (location.CityName != null)
                    {
                        txtCity.Text = location.CityName;
                    }
                    else
                    {
                        txtCity.Text = "";
                    }
                }
            }
        }

        public void ClearData()
        {
            vcmbState.SelectedIndex = -1;
            vcmbCountry.SelectedIndex = -1;
            txtZip.Text = "";
            txtAdd4.Text = "";
            txtAdd3.Text = "";
            txtCity.Text = "";
        }

        private void vtxtSearchZip_LostFocus(object sender, RoutedEventArgs e)
        {

        }

        private void vtxtSearchZip_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter || e.Key == Key.Tab)
            {
                if (vtxtSearchZip.Text.Length > 0)
                {
                    GetZipCodeDetails();
                }
            }
        }








    }
}

